package com.nanbei.lock;

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * @ClassDescription: 读写锁降级  将写锁降级为读锁
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/11/6 9:47
 */
@Slf4j
public class RWLockDemo {
    public static void main(String[] args) {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

        String s;
        writeLock.lock();
        try{
            log.info("写锁开启，开始写数据");
            s = "青花瓷";
            readLock.lock();
            log.info("开启读锁，读取数据");
        }finally {
            writeLock.unlock();  // 释放写锁降级为读锁
        }

        try {
            log.info("写锁已关闭，锁降级为读锁");
            log.info("读取数据{}",s);
        }finally {
            readLock.unlock();
        }

    }
}
